package com.dondedesigns.eh.persistence.dao;

import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.hibernate.Session;
import org.springframework.transaction.annotation.Transactional;

import com.dondedesigns.eh.persistence.User;



@Transactional
public class GenericDAO<T> {

	private EntityManager entityManager;
	
	@PersistenceContext
	public void setEntityManager(EntityManager em) {
		this.entityManager = em;
	}
	
	public EntityManager getEntityManager() {
		return entityManager;
	}

	public void save (T entity) {
		entityManager.persist(entity);
	}
	
	public void delete (Class<T> entityClass, Long entityId) {
		T result = entityManager.find(entityClass, entityId);
		entityManager.remove(result);
	}
	
	public void delete (T entity) {
		entityManager.remove(entity);
	}
	
	public T find (Class<T> entity, Long id) {
		T result = entityManager.find(entity, id);
		return result;
	}
	
	public T merge(T entity) {
		return entityManager.merge(entity);

	}
	
	public void update (T entity) {
		entityManager.merge(entity);
	}
	
	public List<T> select (String hqlString) {
		return entityManager.createQuery(hqlString).getResultList();
	}
	
	public List<T> select (Class<T> entity) {
		Session s = (Session)getEntityManager().getDelegate();
		List<T> result = s.createCriteria(entity).list();
		return result;
	}
	
	public T find (String hqlString, Map<String, String> parameters) {
		Query query = entityManager.createQuery(hqlString);
		
		for (Entry<String, String> parameter : parameters.entrySet()) {
			query.setParameter(parameter.getKey(), parameter.getValue());
		}
		return (T) query.getSingleResult();
	}
	
	public boolean exists (T entity) {
		return entityManager.contains(entity);
	}
	
}
